<template>
  <div class="counselor-dashboard">
    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="banner-content">
        <h1>今日预约 {{ statistics.todayAppointments }}</h1>
        <p>较昨日 <span :class="statistics.appointmentTrend >= 0 ? 'up' : 'down'">{{ Math.abs(statistics.appointmentTrend) }}%</span></p>
        <p>已完成咨询 {{ statistics.completedConsults }} 次，服务学生 {{ statistics.totalStudents }} 人</p>
        <el-button type="primary" size="large" @click="viewSchedule">
          查看完整日程
        </el-button>
      </div>
    </div>

    <!-- 重新设计的内容布局 -->
    <el-row :gutter="20" class="dashboard-content">
      <!-- 左侧：今日预约 + 工作概览 + 快捷操作 -->
      <el-col :span="12">
        <!-- 心理知识 -->
        <el-card class="dashboard-card knowledge-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3><el-icon><Reading /></el-icon>心理知识</h3>
              <el-button text @click="handleViewAllKnowledge">查看全部</el-button>
            </div>
          </template>
          <div class="knowledge-list">
            <el-scrollbar height="620px">
              <div v-for="article in knowledgeList" :key="article.id" class="knowledge-item" @click="handleViewArticle(article.id)">
                <div class="knowledge-image">
                  <el-image 
                    :src="article.coverUrl || defaultCover" 
                    fit="cover"
                  >
                    <template #error>
                      <div class="image-slot">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>
                <div class="knowledge-content">
                  <div class="knowledge-info">
                    <h4>{{ article.title }}</h4>
                    <p>{{ article.description }}</p>
                    <div class="knowledge-meta">
                      <span>
                        <el-icon><Clock /></el-icon>
                        {{ formatDateTime(article.createTime) }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
              <el-empty v-if="!knowledgeList.length" description="暂无心理知识" />
            </el-scrollbar>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：公告 + 数据统计 -->
      <el-col :span="12">
        <!-- 最新公告 -->
        <el-card class="dashboard-card notice-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3><el-icon><Bell /></el-icon>最新公告</h3>
              <el-button text @click="viewAllNotices">查看全部</el-button>
            </div>
          </template>
          <div class="notice-list">
            <el-scrollbar height="120px">
              <div v-for="notice in noticeList" :key="notice.id" class="notice-item" @click="handleViewNotice(notice.id)">
                <div class="notice-title">
                  <span v-if="notice.isImportant" class="important-tag">重要</span>
                  <span>{{ notice.title }}</span>
                </div>
                <span class="notice-time">{{ formatDateTime(notice.createTime) }}</span>
              </div>
              <el-empty v-if="!noticeList.length" description="暂无公告" />
            </el-scrollbar>
          </div>
        </el-card>

        <!-- 咨询统计 -->
        <el-card class="dashboard-card stats-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3><el-icon><TrendCharts /></el-icon>咨询统计</h3>
              <el-radio-group v-model="statisticsPeriod" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="stats-content">
            <!-- 数字统计 -->
            <div class="stats-overview">
              <div class="stat-item">
                <div class="stat-value">{{ statistics.totalAppointments }}</div>
                <div class="stat-label">总预约数</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ statistics.completedConsults }}</div>
                <div class="stat-label">已完成咨询</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ statistics.totalStudents }}</div>
                <div class="stat-label">服务学生数</div>
              </div>
            </div>
            
            <!-- 图表展示 -->
            <div class="stats-charts">
              <div class="chart-container">
                <div ref="appointmentTrendChart" class="chart"></div>
              </div>
              <div class="chart-container">
                <div ref="consultTypeChart" class="chart"></div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { getArticleList } from '@/api/article'
import dayjs from 'dayjs'
import { getCounselorStatistics, getTodaySchedule, getTodoList } from '@/api/dashboard'
import type { EChartsType } from 'echarts/core'
import * as echarts from 'echarts/core'
import {
  BarChart,
  BarSeriesOption,
  PieChart,
  PieSeriesOption
} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  TitleComponentOption,
  TooltipComponentOption,
  GridComponentOption,
  LegendComponentOption
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { 
  Bell, 
  Reading, 
  Picture,
  Clock, 
  TrendCharts 
} from '@element-plus/icons-vue'

// 注册必需的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  PieChart,
  CanvasRenderer
])

// 定义图表配置类型
type ECOption = echarts.ComposeOption<
  | BarSeriesOption
  | PieSeriesOption
  | TitleComponentOption
  | TooltipComponentOption
  | GridComponentOption
  | LegendComponentOption
>

interface Notice {
  id: number
  title: string
  isImportant: boolean
  createTime: string
}

interface Statistics {
  totalAppointments: number
  totalStudents: number
  todayAppointments: number
  pendingAppointments: number
  appointmentTrend: number
  completedConsults: number
  satisfaction: string
  weeklyHours: number
  weeklyAppointments: number[]
  consultationTypes: Array<{
    value: number
    name: string
  }>
}

interface Appointment {
  id: number
  studentName: string
  studentAvatar: string
  appointmentTime: string
  time: string
  status: string
}

interface TodoItem {
  id: number
  title: string
  type: 'urgent' | 'normal'
  createTime: string
}

const router = useRouter()
const noticeList = ref<Notice[]>([])
const statistics = ref<Statistics>({
  totalAppointments: 0,
  totalStudents: 0,
  todayAppointments: 0,
  pendingAppointments: 0,
  appointmentTrend: 0,
  completedConsults: 0,
  satisfaction: '0%',
  weeklyHours: 0,
  weeklyAppointments: [],
  consultationTypes: []
})

const todaySchedule = ref<Appointment[]>([])
const todoList = ref<TodoItem[]>([])
const statisticsPeriod = ref('week')

// 图表引用
const appointmentTrendChart = ref()
const consultTypeChart = ref()
let trendChartInstance: EChartsType | null = null
let typeChartInstance: EChartsType | null = null

// 心理知识列表数据
const knowledgeList = ref<any[]>([])
const defaultCover = ref('/src/assets/images/default-cover.jpg')

// 加载公告列表
const loadNotices = async () => {
  try {
    const { data } = await getArticleList({
      pageNum: 1,
      pageSize: 5,
      category: 'NOTICE',
      status: '1'
    })
    if (data && data.records) {
      noticeList.value = data.records
      console.log('Loaded notices:', data.records)
    }
  } catch (error) {
    console.error('加载公告失败:', error)
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const { data } = await getCounselorStatistics()
    statistics.value = data
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载今日预约安排
const loadTodaySchedule = async () => {
  try {
    const { data } = await getTodaySchedule()
    todaySchedule.value = data.map((item: any) => ({
      ...item,
      time: formatTime(item.appointmentTime)
    }))
  } catch (error) {
    console.error('加载今日预约失败:', error)
  }
}

// 加载待处理事项
const loadTodoList = async () => {
  try {
    const { data } = await getTodoList()
    todoList.value = data
  } catch (error) {
    console.error('加载待处理事项失败:', error)
  }
}

// 获取心理知识列表
const fetchKnowledgeList = async () => {
  try {
    const { data } = await getArticleList({
      category: 'KNOWLEDGE',
      status: '1',
      pageSize: 10,
      pageNum: 1,
      orderBy: 'create_time desc'
    })
    knowledgeList.value = data.records
  } catch (error) {
    console.error('获取心理知识列表失败:', error)
  }
}

// 查看全部心理知识
const handleViewAllKnowledge = () => {
  router.push('/notice/articlelist')
}

// 查看文章详情
const handleViewArticle = (id: number) => {
  router.push(`/notice/detail/${id}`)
}

// 格式化方法
const formatDateTime = (time: string): string => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const formatTime = (time: string): string => {
  return dayjs(time).format('HH:mm')
}

// 状态相关方法
const getStatusType = (status: string): string => {
  const map: Record<string, string> = {
    'PENDING': 'warning',
    'CONFIRMED': 'success',
    'CANCELLED': 'info',
    'COMPLETED': 'success'
  }
  return map[status] || 'info'
}

const getStatusText = (status: string): string => {
  const map: Record<string, string> = {
    'PENDING': '待确认',
    'CONFIRMED': '已确认',
    'CANCELLED': '已取消',
    'COMPLETED': '已完成'
  }
  return map[status] || status
}

// 事件处理方法
const viewSchedule = () => {
  router.push('/counseling/schedule')
}

const viewAllNotices = () => {
  router.push('/notice/articlelist')
}

const handleViewNotice = (id: number) => {
  router.push(`/notice/detail/${id}`)
}

const getTimelineItemType = (status: string): '' | 'primary' | 'success' | 'warning' | 'danger' | 'info' => {
  const map: Record<string, any> = {
    'pending': 'warning',
    'confirmed': 'primary',
    'completed': 'success',
    'cancelled': 'info'
  }
  return map[status] || ''
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!appointmentTrendChart.value) return
  trendChartInstance = echarts.init(appointmentTrendChart.value)
  
  const option: ECOption = {
    grid: {
      top: 30,
      bottom: 30,
      left: '3%',
      right: '4%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      axisLine: {
        lineStyle: {
          color: '#909399'
        }
      }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '预约数',
      type: 'bar',
      barWidth: '60%',
      data: statistics.value.weeklyAppointments || [0, 0, 0, 0, 0, 0, 0],
      itemStyle: {
        color: '#1890ff'
      }
    }]
  }
  
  trendChartInstance?.setOption(option)
}

// 初始化类型分布图表
const initTypeChart = () => {
  if (!consultTypeChart.value) return
  typeChartInstance = echarts.init(consultTypeChart.value)
  
  const option: ECOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'center',
      textStyle: {
        color: '#606266'
      }
    },
    series: [{
      name: '咨询类型',
      type: 'pie',
      radius: ['45%', '70%'],
      center: ['40%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 4,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '14',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: statistics.value.consultationTypes || []
    }]
  }
  
  typeChartInstance?.setOption(option)
}

// 监听统计周期变化
watch(statisticsPeriod, () => {
  // 这里可以重新加载数据并更新图表
  loadStatistics()
})

// 监听统计数据变化，更新图表
watch(() => statistics.value, (newStats) => {
  nextTick(() => {
    if (trendChartInstance && newStats.weeklyAppointments) {
      trendChartInstance.setOption({
        series: [{
          data: newStats.weeklyAppointments
        }]
      })
    }
    if (typeChartInstance && newStats.consultationTypes) {
      typeChartInstance.setOption({
        series: [{
          data: newStats.consultationTypes
        }]
      })
    }
  })
}, { deep: true })

// 在组件卸载时销毁图表实例
onBeforeUnmount(() => {
  if (trendChartInstance) {
    trendChartInstance.dispose()
  }
  if (typeChartInstance) {
    typeChartInstance.dispose()
  }
})

onMounted(() => {
  loadStatistics()
  loadTodaySchedule()
  loadTodoList()
  loadNotices()
  fetchKnowledgeList()
  nextTick(() => {
    initTrendChart()
    initTypeChart()
    
    // 修改 resize 监听
    window.addEventListener('resize', () => {
      if (trendChartInstance) {
        trendChartInstance.resize()
      }
      if (typeChartInstance) {
        typeChartInstance.resize()
      }
    })
  })
})
</script>

<style lang="scss" scoped>
.counselor-dashboard {
  .welcome-banner {
    height: 240px;
    background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
    border-radius: 8px;
    margin-bottom: 20px;
    padding: 40px;
    color: white;
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(45deg, rgba(255,255,255,0.1) 25%, transparent 25%, transparent 50%, rgba(255,255,255,0.1) 50%, rgba(255,255,255,0.1) 75%, transparent 75%, transparent);
      background-size: 4px 4px;
      opacity: 0.2;
    }

    .banner-content {
      position: relative;
      z-index: 1;

      h1 {
        font-size: 32px;
        margin: 0 0 16px;
        font-weight: 600;
      }

      p {
        font-size: 16px;
        margin: 8px 0;
        opacity: 0.9;

        .up {
          color: #95eb7d;
          &::before { content: '+'; }
        }
        .down {
          color: #ff9292;
          &::before { content: '-'; }
        }
      }

      .el-button {
        margin-top: 24px;
        padding: 12px 24px;
        font-size: 16px;
      }
    }
  }

  .dashboard-content {
    :deep(.el-card) {
      border: none !important;
      
      .el-card__header {
        padding: 0;
        border-bottom: none;
      }
    }

    .dashboard-card {
      border: none;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      margin-bottom: 16px;
      border-radius: 8px;

      &.schedule-card {
        height: 666px;
        display: flex;
        flex-direction: column;

        .schedule-timeline {
          flex: 1;
          padding: 16px;
          overflow-y: auto;
        }

        .quick-actions {
          padding: 16px;
          background: #fff;
        }
      }

      &.notice-card {
        height: 210px;
        margin-bottom: 16px;

        .notice-list {
          padding: 0 16px;
          max-height: 150px;
          overflow-y: auto;
        }

        .notice-item {
          padding: 8px 0;
          border-bottom: 1px solid #f0f0f0;
          cursor: pointer;
          transition: background-color 0.3s;

          &:last-child {
            border-bottom: none;
          }

          &:hover {
            background-color: #f5f7fa;
          }
        }
      }

      &.stats-card {
        height: 440px;
        
        .stats-content {
          padding: 20px;

          .stats-overview {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px;
            margin-bottom: 24px;

            .stat-item {
              text-align: center;
              padding: 12px;
              background: #f8f9fa;
              border-radius: 8px;

              .stat-value {
                font-size: 24px;
                font-weight: 600;
                color: var(--el-color-primary);
                margin-bottom: 8px;
              }

              .stat-label {
                font-size: 14px;
                color: #909399;
              }
            }
          }

          .stats-charts {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            height: 280px;
            margin-top: 24px;

            .chart-container {
              background: #f8f9fa;
              border-radius: 8px;
              padding: 12px;
              .chart {
                width: 100%;
                height: 100%;
              }
            }
          }
        }
      }

      &.knowledge-card {
        height: 666px;
        
        .knowledge-list {
          padding: 16px;
          
          .knowledge-item {
            display: flex;
            margin-bottom: 16px;
            border-radius: 8px;
            overflow: hidden;
            cursor: pointer;
            transition: all 0.3s;
            background: #fff;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            height: 140px;
            
            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            }
            
            .knowledge-image {
              width: 240px;
              height: 140px;
              flex-shrink: 0;
              
              .el-image {
                width: 100%;
                height: 100%;
              }
              
              .image-slot {
                display: flex;
                justify-content: center;
                align-items: center;
                width: 100%;
                height: 100%;
                background: #f5f7fa;
                color: #909399;
                font-size: 30px;
              }
            }
            
            .knowledge-content {
              flex: 1;
              padding: 16px;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              
              .knowledge-info {
                h4 {
                  margin: 0 0 8px;
                  font-size: 16px;
                  font-weight: 500;
                  color: #303133;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
                
                p {
                  margin: 0 0 8px;
                  font-size: 14px;
                  color: #606266;
                  line-height: 1.6;
                  overflow: hidden;
                  display: -webkit-box;
                  -webkit-box-orient: vertical;
                  -webkit-line-clamp: 2;
                  line-clamp: 2;
                }
                
                .knowledge-meta {
                  font-size: 12px;
                  color: #909399;
                  
                  span {
                    display: flex;
                    align-items: center;
                    gap: 4px;
                  }
                }
              }
            }
          }
        }
      }

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        position: relative;
        
        &::after {
          content: '';
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          height: 1px;
          background-color: #f0f0f0;
        }

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          display: flex;
          align-items: center;
          gap: 8px;

          .el-icon {
            font-size: 18px;
            color: var(--el-color-primary);
          }
        }
      }

      .notice-item {
        .notice-title {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 4px;

          .important-tag {
            padding: 2px 6px;
            background-color: #ff4d4f;
            color: white;
            font-size: 12px;
            border-radius: 2px;
          }
        }

        .notice-time {
          font-size: 12px;
          color: #909399;
        }
      }

      .quick-actions {
        .action-row {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 12px;

          .el-button {
            height: 60px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 8px;

            .el-icon {
              font-size: 20px;
            }
          }
        }
      }
    }
  }
}
</style> 